package com.ophiux.controller;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    List<User> userList;


    @GetMapping("/userList")
    public List<User> userList(){
        if(userList==null||userList.size()<1){
            userList = new ArrayList<>();
            User user = new User();
            user.setId(1);
            user.setName("张三");
            user.setAge(34);

            User user1 = new User();
            user1.setId(2);
            user1.setName("李四");
            user1.setAge(35);

            userList.add(user);
            userList.add(user1);
        }
        return userList;
    }

    @PostMapping
    public Boolean save(@RequestBody User user){
        userList.add(user);
        return true;
    }

    @PutMapping
    public Boolean update(@RequestBody User user){
        List<User> userList1 = userList.stream().filter(user1 -> user1.getId() != user.getId()).collect(Collectors.toList());
        userList1.add(user);
        this.userList = userList1;
        return true;
    }

    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable("id") int id){
        List<User> userList1 = userList.stream().filter(user1 -> user1.getId() != id).collect(Collectors.toList());
        this.userList = userList1;
        return true;
    }


}
